﻿using Abp.Domain.Repositories;
using SportsPlatform.Base;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Query.PermissionManagement.AuthorizationInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.AuthorizationInfo;
using Abp.Collections.Extensions;
using Abp.Application.Services;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SportsPlatform.Helpers;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System.IO;
using SportsPlatform.Enums;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 授权信息表接口实现
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class AuthorizationService : SportsPlatformAppServiceBase, IAuthorizationService
    {
        private readonly IRepository<CompanyInfo, Guid> _companyinfoRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly IRepository<AuthorizationInfo, Guid> _authorizationRepository;

        private readonly IWebHostEnvironment _webHostEnvironment;
        /// <summary>
        /// 构造
        /// </summary>
        public AuthorizationService(IRepository<CompanyInfo, Guid> companyinfoRepository, IRepository<UserInfo, Guid> userinfoRepository,
            IRepository<AuthorizationInfo, Guid> authorizationRepository, IHttpContextAccessor context, IWebHostEnvironment env) : base(context)
        {
            _webHostEnvironment = env;
            _companyinfoRepository = companyinfoRepository;
            _userinfoRepository = userinfoRepository;
            _authorizationRepository = authorizationRepository;
        }

        /// <summary>
        /// 新增授权信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddAuthorizationInfo(AddAuthorizationInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //判断授权数量是否还有
                var companyinfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == token.CompanyId);
                if ((companyinfo.ClientAuthorizationCodeNumber - _authorizationRepository.GetAllList(info => info.CompanyId == token.CompanyId && (info.States == (int)AuthorizationStateEnum.审核通过 || info.States == (int)AuthorizationStateEnum.待审核)).Count) <= 0)
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "未审核和授权的数量已达上限！不能申请";
                    return baseResultDto;
                }
                var authorizationInfo = ObjectMapper.Map<AuthorizationInfo>(query);
                authorizationInfo.CreateTime = DateTime.Now;
                authorizationInfo.CreateUserId = token.Id;
                authorizationInfo.UserId = token.Id;
                authorizationInfo.CompanyId = (Guid)token.CompanyId;
                authorizationInfo.States = (int)AuthorizationStateEnum.待审核;
                await _authorizationRepository.InsertAsync(authorizationInfo);
                baseResultDto.IsSuccess = true;
                baseResultDto.Code = HttpResultCode.Success;
                baseResultDto.Message = "新增成功！";
            }
            catch (Exception ex)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = ex.Message.ToString();
            }
            return baseResultDto;
        }
        /// <summary>
        /// 批量/单个审核
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AuthorizationSteats(StatusChangeAuthorizationInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.SqlError;
                int failnumber = 0;//更新失败数量
                string failid = "";//更新失败Id
                if (query.List != null && query.List.ToList().Count > 0)
                {
                    var idlist = query.List.ToList();
                    var companyinfolist = await _companyinfoRepository.GetAllListAsync();
                    for (int i = 0; i < idlist.Count; i++)
                    {
                        var authorizationinfo = await _authorizationRepository.FirstOrDefaultAsync(info => info.Id.ToString().Equals(idlist[i]));
                        if (authorizationinfo != null)
                        {
                            //审核通过插入相关信息
                            if (query.States == AuthorizationStateEnum.审核通过)
                            {
                                authorizationinfo.AuthorizationCode = CommonHelper.MD5Encryption(authorizationinfo.AuthorizationSerialNumber + Guid.NewGuid(),16);
                                var secretkey = CommonHelper.GetRsaKeyPair();
                                authorizationinfo.PrivateKey = CommonHelper.AesEncrypt(secretkey.Item1, authorizationinfo.AuthorizationCode);
                                authorizationinfo.PublicKey = CommonHelper.AesEncrypt(secretkey.Item2, authorizationinfo.AuthorizationCode);
                                var enddatetime = companyinfolist.FirstOrDefault(info => info.Id == authorizationinfo.CompanyId).AuthorizeEndTIme;
                                authorizationinfo.ExpireTime = enddatetime;
                                authorizationinfo.AuthorizationFileUrl = SaveAuthorizationFile(CommonHelper.AesDecrypt(authorizationinfo.PublicKey, authorizationinfo.AuthorizationCode), authorizationinfo.AuthorizationSerialNumber, enddatetime);
                            }
                            authorizationinfo.States = (int)query.States;
                            authorizationinfo.UpdateTime = DateTime.Now;
                            authorizationinfo.UpdateUserId = token.Id;
                            await _authorizationRepository.UpdateAsync(authorizationinfo);
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "更新成功！";
                        }
                        else
                        {
                            failnumber++;
                            failid += string.IsNullOrEmpty(failid) ? idlist[i].ToString() : "," + idlist[i].ToString();

                        }
                    }
                    if (failnumber != 0)
                    {
                        baseResultDto.Message = string.Format("一共更新{0}条，失败{1}条,失败id:{2}!", idlist.Count.ToString(), failnumber.ToString(), failid);
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "IdList不能为空！";
                }
            }
            catch (Exception ex)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = ex.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 商户授权验证密码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AuthorizationVerificationPassword(AuthorizationVerificationPasswordQuery query)
        {
            BaseResultDto baseResultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                if ((token.CompanyId == null || token.CompanyId == Guid.Empty) && (query.CompanyId == null || query.CompanyId == Guid.Empty))
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "非平台验证或传入商户Id";
                }
                var companyinfo = (await _companyinfoRepository.GetAllListAsync())
                    .WhereIf(query.CompanyId != null, info => info.Id == query.CompanyId)
                    .WhereIf(query.CompanyId == null && token.CompanyId != null, info => info.Id == token.CompanyId)
                    .ToList().FirstOrDefault();
                if (companyinfo != null)
                {
                    var userinfo = await _userinfoRepository.FirstOrDefaultAsync(companyinfo.ContactsUserId);
                    if (userinfo != null)
                    {
                        if (userinfo.PassWord.Equals(query.Password))
                        {
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "验证成功！";
                        }
                        else
                        {
                            baseResultDto.IsSuccess = false;
                            baseResultDto.Code = HttpResultCode.Fail;
                            baseResultDto.Message = "输入密码与超级管理员密码不对！";
                        }
                    }
                    else
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.NotData;
                        baseResultDto.Message = "未查询到商户所属用户信息！";
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.NotData;
                    baseResultDto.Message = "未查询到商户信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 获取授权码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetAuthorizationCodeDto>> GetAuthorizationCode(GetAuthorizationCodeQuery query)
        {
            ResultDto<GetAuthorizationCodeDto> resultDto = new();
            try
            {
                var authinfo = await _authorizationRepository.FirstOrDefaultAsync(query.Id);
                if (authinfo != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    resultDto.Data = new() { AuthorizationCode = authinfo.AuthorizationCode };
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取授权商户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetAuthorizationCompanyInfoDto>> GetAuthorizationCompanyInfo(GetAuthorizationCompanyInfoQuery query)
        {
            ResultDto<GetAuthorizationCompanyInfoDto> resultDto = new();
            try {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var companylist = (await _companyinfoRepository.GetAllListAsync())
                    .WhereIf(query.CompanyId != null, info => info.Id == query.CompanyId)
                    .WhereIf(query.CompanyId == null && token.CompanyId != null, info => info.Id == token.CompanyId)
                    .ToList();
                if (companylist != null && companylist.Count > 0)
                {
                    if (companylist.Count == 1)
                    {
                        var authlist = await _authorizationRepository.GetAllListAsync();
                        var userlist = await _userinfoRepository.GetAllListAsync();
                        GetAuthorizationCompanyInfoDto dto = new();
                        foreach (var item in companylist)
                        {
                            dto.CompanyName = item.CompanyName;
                            dto.AuthorizeTIme = item.AuthorizeBeginTime.ToString("yyyy-MM-dd") + "~" + item.AuthorizeEndTIme.ToString("yyyy-MM-dd");
                            dto.ClientAuthorizationCodeNumber = item.ClientAuthorizationCodeNumber.ToString() + "台";
                            dto.UsageTime = item.UsageTime;
                            dto.SurplusAuthorization = (item.ClientAuthorizationCodeNumber - authlist.Where(info => info.CompanyId == item.Id).ToList().Count).ToString() + "台";
                            dto.DaysRemaining = item.AuthorizeEndTIme < DateTime.Now ? "0天" : Math.Abs(((TimeSpan)(item.AuthorizeEndTIme - DateTime.Now)).Days).ToString() + "天";
                            dto.CustomerServiceTel = "400-888-888";
                            dto.CompanyUserTel = userlist.FirstOrDefault(info => info.Id == item.ContactsUserId)?.UserTel;
                            dto.CompanyUserName= userlist.FirstOrDefault(info => info.Id == item.ContactsUserId)?.UserName;
                        }
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "查询成功！";
                        resultDto.Data = dto;

                    }
                    else {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "请传入商户Id！";
                    }
                }
                else {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取授权信息详细列表返回
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetAuthorizationDetailedInfoListDto>> GetAuthorizationDetailedInfoList(GetAuthorizationInfoQuery query)
        {
            PagePagingDto<GetAuthorizationDetailedInfoListDto> pagePagingDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var authorizationinfolist = (await _authorizationRepository.GetAllListAsync())
                    .WhereIf(query.CompanyId != null, info => info.CompanyId == query.CompanyId)
                    .WhereIf(query.CompanyId == null && token.CompanyId != null, info => info.CompanyId == token.CompanyId)
                    .WhereIf(query.States != null, info => info.States == (int)query.States)
                    .WhereIf(!string.IsNullOrEmpty(query.Name), info => _userinfoRepository.FirstOrDefault(userinfo => userinfo.Id == info.UserId).UserName.Contains(query.Name) || _companyinfoRepository.FirstOrDefault(companyinfo => companyinfo.Id == info.CompanyId).CompanyName.Contains(query.Name))
                    .OrderByDescending(info => info.CreateTime)
                    .ToList();
                var authorizationinfopage = authorizationinfolist
                  .Skip((query.PageIndex - 1) * query.PageSize)
                  .Take(query.PageSize)
                  .ToList();
                if (authorizationinfopage != null && authorizationinfopage.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.Message = "查询成功！";
                    pagePagingDto.TotalCount = authorizationinfolist.Count;
                    var pagedtolist = ObjectMapper.Map<List<GetAuthorizationDetailedInfoListDto>>(authorizationinfopage);
                    var userinfolist = await _userinfoRepository.GetAllListAsync();
                    var companyinfolist=await _companyinfoRepository.GetAllListAsync();
                    var authlist = await _authorizationRepository.GetAllListAsync();
                    pagedtolist.ForEach(item =>
                    {
                        var userinfo = userinfolist.FirstOrDefault(info => info.Id == item.UserId);
                        var companyinfo = companyinfolist.FirstOrDefault(info => info.Id == item.CompanyId);
                        item.UserName = userinfo.UserName;
                        item.UserTel = $"{userinfo.UserTel.Substring(0, 3)}****{userinfo.UserTel.Substring(userinfo.UserTel.Length - 4, 4)}";
                        item.CompanyName = companyinfo.CompanyName;
                        item.SurplusAuthorization = companyinfo.ClientAuthorizationCodeNumber - authlist.Where(info => info.CompanyId == item.CompanyId && info.States == (int)AuthorizationStateEnum.审核通过).ToList().Count;
                        item.UpdateUserName = item.UpdateUserId != null ? (userinfolist.FirstOrDefault(info => info.Id == item.UpdateUserId).UserName) : "";
                        item.CreateTime = authlist.FirstOrDefault(info=>info.Id==item.Id).CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                        item.UpdateTime = authlist.FirstOrDefault(info => info.Id == item.Id).UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "";
                    });
                    pagePagingDto.Data = pagedtolist;
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未获取到相关客户授权信息！";
                    return pagePagingDto;
                }
            }
            catch (Exception ex)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = ex.Message.ToString();
            }
            return pagePagingDto;
        }

        ///// <summary>
        ///// 获取授权信息列表返回
        ///// </summary>
        ///// <param name="query"></param>
        ///// <returns></returns>
        //public async Task<PagePagingDto<GetAuthorizationInfoListDto>> GetAuthorizationList(GetAuthorizationInfoQuery query)
        //{
        //    PagePagingDto<GetAuthorizationInfoListDto> pagePagingDto = new PagePagingDto<GetAuthorizationInfoListDto>();
        //    try
        //    {
        //        var authorizationinfolist = (await _authorizationRepository.GetAllListAsync(info => info.CompanyId == query.CompanyId && info.States == 1))
        //            .OrderByDescending(info => info.CreateTime).ToList();
        //        var authorizationinfopage = authorizationinfolist
        //          .Skip((query.PageIndex - 1) * query.PageSize)
        //          .Take(query.PageSize)
        //          .ToList();
        //        if (authorizationinfopage != null && authorizationinfopage.Count > 0)
        //        {
        //            pagePagingDto.IsSuccess = true;
        //            pagePagingDto.Code = HttpResultCode.Success;
        //            pagePagingDto.TotalCount = authorizationinfolist.Count;
        //            var pagedtolist = ObjectMapper.Map<List<GetAuthorizationInfoListDto>>(authorizationinfopage);

        //            var userinfolist = await _userinfoRepository.GetAllListAsync();
        //            var companyinfolist = await _companyinfoRepository.GetAllListAsync();
        //            var authlist = await _authorizationRepository.GetAllListAsync(info => info.States == 1);

        //            pagedtolist.ForEach(item =>
        //            {
        //                var userinfo = userinfolist.FirstOrDefault(info => info.Id == item.UserId);
        //                var companyinfo = companyinfolist.FirstOrDefault(info => info.Id == item.CompanyId);
        //                item.UserName = userinfo.UserName;
        //                item.UserTel = userinfo.UserTel;
        //                item.CompanyName = companyinfo.CompanyName;
        //                item.AuthorizeTIme = companyinfo.AuthorizeBeginTime.ToString("yyyy-MM-dd") + "~" + companyinfo.AuthorizeEndTIme.ToString("yyyy-MM-dd");
        //                item.UsageTime = companyinfo.UsageTime;
        //                item.ClientAuthorizationCodeNumber = companyinfo.ClientAuthorizationCodeNumber.ToString() + "台";
        //                item.SurplusAuthorization = (companyinfo.ClientAuthorizationCodeNumber - authlist.Where(info => info.CompanyId == item.CompanyId).ToList().Count).ToString() + "台";
        //                item.DaysRemaining = companyinfo.AuthorizeEndTIme < DateTime.Now ? "0天" : Math.Abs(((TimeSpan)(companyinfo.AuthorizeEndTIme - DateTime.Now)).Days).ToString() + "天";
        //                var contactsuserinfo = userinfolist.FirstOrDefault(info => info.Id == companyinfo.ContactsUserId);
        //                item.CompanyUserName = contactsuserinfo?.UserName;
        //                item.CompanyUserTel = contactsuserinfo?.UserTel;
        //            });
        //            pagePagingDto.Data = pagedtolist;
        //        }
        //        else
        //        {
        //            var companyinfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == query.CompanyId);
        //            if (companyinfo != null)
        //            {
        //                pagePagingDto.IsSuccess = true;
        //                pagePagingDto.Code = HttpResultCode.Success;
        //                pagePagingDto.TotalCount = 0;
        //                pagePagingDto.Data = new List<GetAuthorizationInfoListDto>()
        //                { new GetAuthorizationInfoListDto()
        //                {
        //                CompanyId=companyinfo.Id,
        //                CompanyName = companyinfo.CompanyName,
        //                UsageTime=companyinfo.UsageTime,
        //                AuthorizeTIme = companyinfo.AuthorizeBeginTime.ToString("yyyy-MM-dd") + "~" + companyinfo.AuthorizeEndTIme.ToString("yyyy-MM-dd"),
        //                DaysRemaining =  companyinfo.AuthorizeEndTIme < DateTime.Now ? "0天" :Math.Abs(((TimeSpan)(companyinfo.AuthorizeEndTIme - DateTime.Now)).Days).ToString() + "天",
        //                ClientAuthorizationCodeNumber = companyinfo.ClientAuthorizationCodeNumber.ToString() + "台",
        //                SurplusAuthorization=companyinfo.ClientAuthorizationCodeNumber.ToString() + "台",
        //                 CompanyUserName = _userinfoRepository.FirstOrDefault(info => info.Id == companyinfo.ContactsUserId).UserName,
        //                CompanyUserTel = _userinfoRepository.FirstOrDefault(info => info.Id == companyinfo.ContactsUserId).UserTel
        //                } };
        //            }
        //            else
        //            {
        //                pagePagingDto.IsSuccess = false;
        //                pagePagingDto.Code = HttpResultCode.Fail;
        //                pagePagingDto.Message = "传入客户Id有误！";
        //            }
        //            return pagePagingDto;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        pagePagingDto.IsSuccess = false;
        //        pagePagingDto.Code = HttpResultCode.Error;
        //        pagePagingDto.Message = ex.Message.ToString();
        //    }
        //    return pagePagingDto;
        //}

        /// <summary>
        /// 获取用户授权状态
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetUserAuthorizationDto>> GetUserAuthorization(GetUserAuthorizationQuery query)
        {
            ResultDto<GetUserAuthorizationDto> resultDto = new ResultDto<GetUserAuthorizationDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var ret = await _authorizationRepository.FirstOrDefaultAsync(info => info.AuthorizationSerialNumber == query.AuthorizationSerialNumber && info.CompanyId == token.CompanyId);
                if (ret != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    resultDto.Data = new GetUserAuthorizationDto() { States = ret.States };
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到该设备的审核信息！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取用户授权文件
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetUserAuthorizationFileDto>> GetUserAuthorizationFile(GetUserAuthorizationFileQuery query)
        {
            ResultDto<GetUserAuthorizationFileDto> resultDto = new ResultDto<GetUserAuthorizationFileDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var ret = await _authorizationRepository.FirstOrDefaultAsync(info => info.CompanyId == token.CompanyId && info.AuthorizationCode == query.AuthorizationCode && info.AuthorizationSerialNumber == query.AuthorizationSerialNumber);
                if (ret != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    resultDto.Data = new GetUserAuthorizationFileDto() { AuthorizationFileUrl = ret.AuthorizationFileUrl, PrivateKey = ret.PrivateKey };
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到该设备的审核信息！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 保存授权文件
        /// </summary>
        /// <param name="PubKey">公钥</param>
        /// <param name="MachineInfo">机器码</param>
        /// <param name="expireTime">过期时间</param>
        /// <returns>授权文件地址</returns>
        private string SaveAuthorizationFile(string PubKey, string MachineInfo, DateTime expireTime)
        {
            try
            {
                //生成授权码
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["MachineInfo"] = MachineInfo;
                dic["ExpireTime"] = expireTime.ToString("yyyy-MM-dd");

                var json = JsonConvert.SerializeObject(dic);
                var signer = CommonHelper.RSAEncrypt(json, PubKey);


                //保存授权文件dll
                //相对路径
                string url = "/AuthorizationFile/" + DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + "/" + Guid.NewGuid().ToString() + "/";
                //文件名
                string filename= "AuthorizationFile.txt";
                //绝对路径
                string path = _webHostEnvironment.WebRootPath + url;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                File.WriteAllText(path + filename, signer.Trim());
                return Path.Combine(url, filename);
            }
            catch
            {
                return "";
            }
        }
    }
}
